/**
 * 
 */
package me.joshua.tools4j.web.common;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * @author <a href="mailto:daonan.zhan@gmail.com">Joshua Zhan</a>
 * 
 */
public class CsrfRequestMatcher implements RequestMatcher {

	private Pattern			allowedMethods	= Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

	private List<String>	protectedUrls;
	private RequestMatcher	urlMatcher;

	@PostConstruct
	public void init() {
		List<RequestMatcher> matchers = new LinkedList<RequestMatcher>();
		if (null != protectedUrls) {
			for (String url : protectedUrls) {
				matchers.add(new AntPathRequestMatcher(url));
			}
		}
		urlMatcher = new OrRequestMatcher(matchers);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.web.util.matcher.RequestMatcher#matches(
	 * javax.servlet.http.HttpServletRequest)
	 */
	public boolean matches(HttpServletRequest request) {
		if (urlMatcher.matches(request)) {
			return true;
		}

		return !allowedMethods.matcher(request.getMethod()).matches();
	}

	public void setProtectedUrls(List<String> protectedUrls) {
		this.protectedUrls = protectedUrls;
	}

}
